﻿# coding: UTF-8
# Name: 主模块
# Author: LYC
# Created:

import sys
import argparse
import jieba
import collections
import math

class Files(object):
    """
    文件类
    """
    LineItem = collections.namedtuple(u"LineItem", (u"words", u"counter"))

    @classmethod
    def get_lineitem(cls, txt, cut_all):
        """获得一个LineItem对象"""
        words = tuple(i for i in jieba.cut(txt, cut_all) if i)
        counter = collections.Counter(words)

        return cls.LineItem(words, counter)


    def __init__(self, path, cut_all=False):
        super(Files, self).__init__()

        self.path = path
        self.cut_all = cut_all
        self._lines = None

    @property
    def lines(self):
        """文件行"""
        if self._lines == None:
            with open(self.path, u"rt") as fp:
                self._lines = [l.strip() for l in fp if l.strip()]

        return self._lines

    @property
    def text(self):
        """文件内容"""
        return u"\n".join(self.lines)

    def __iter__(self):
        """迭代器"""
        return (self.get_lineitem(l, self.cut_all) for l in self.lines)

def compare(item1, item2):
    """根据余弦定理获取两个向量的余弦"""
    keys_set = set(item1.counter.keys() + item2.counter.keys())
    vt1 = tuple(item1.counter.get(k, 0) for k in keys_set)
    vt2 = tuple(item2.counter.get(k, 0) for k in keys_set)

    s1 = reduce(lambda s, i:s+i[0]*i[1], zip(vt1, vt2), 0.0)
    a1 = reduce(lambda s, i:s+i**2, vt1, 0.0)
    b1 = reduce(lambda s, i:s+i**2, vt2, 0.0)

    return s1/(math.sqrt(a1) * math.sqrt(b1)) * 100

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument(u"-b", u"--base", nargs="+", action=u"store", help=u"The base point of others")
    parser.add_argument(u"-f", u"--files", nargs="+", action=u"store", help=u"The files which to compare")

    args = parser.parse_args(argv[1:])

    jieba.initialize()

    file_base = Files(args.base[0])
    files = [Files(p) for p in args.files if p]

    print u"Base: %s" % file_base.path

    for f in files:
        print u"Scaning: %s" % f.path
        print u"=" * 10, u"out", u"=" * 10
        for n, i in enumerate(zip(file_base, f)):
            bl, fl = i
            print u"Line: %d" % (n+1), u"Result: %.2f%%" % compare(bl, fl)
            print u"Base Line: %s" % u"/ ".join(bl.words)
            print u"Target Line: %s" % u"/ ".join(fl.words)
            print u""

        print u"=" * 10, u"End", u"=" * 10

if __name__ == '__main__':
    main(sys.argv)
